import { defineStore } from 'pinia'
import { login as loginApi, logout as logoutApi } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    // 用户信息
    userInfo: {
      id: '',
      username: '',
      name: '',
      image: '',
      roleLabel: ''
    },
    // token
    token: '',
    // 登录状态
    isLoggedIn: false
  }),

  getters: {
    // 获取用户角色
    roleLabel: (state) => state.userInfo.roleLabel,
    // 获取用户名
    name: (state) => state.userInfo.name,
    // 获取用户ID
    userId: (state) => state.userInfo.id
  },

  actions: {
    /**
     * 用户登录
     * @param {Object} credentials 登录凭证
     * @param {string} credentials.username 用户名
     * @param {string} credentials.password 密码
     * @returns {Promise} 登录结果
     */
    async login(credentials) {
      try {
        const response = await loginApi(credentials)
        if (response.code === 1) {
          const { id, username, name, image, roleLabel, token } = response.data
          
          // 更新store中的用户信息
          this.userInfo = {
            id,
            username,
            name,
            image,
            roleLabel
          }
          
          this.token = token
          this.isLoggedIn = true
          
          // 将用户信息和token存储到localStorage中
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          localStorage.setItem('token', token)
          
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.msg || '登录失败' }
        }
      } catch (error) {
        return { success: false, message: error.message || '登录失败，请稍后重试' }
      }
    },

    /**
     * 用户登出
     * @returns {Promise} 登出结果
     */
    async logout() {
      try {
        // 调用登出接口
        await logoutApi()
      } catch (error) {
      } finally {
        // 无论接口调用是否成功，都清除本地存储和状态
        this.clearUserInfo()
      }
    },

    /**
     * 清除用户信息
     */
    clearUserInfo() {
      this.userInfo = {
        id: '',
        username: '',
        name: '',
        image: '',
        roleLabel: ''
      }
      this.token = ''
      this.isLoggedIn = false
      
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
    },

    /**
     * 从本地存储恢复用户信息
     */
    recoverUserInfo() {
      const token = localStorage.getItem('token')
      const userInfoStr = localStorage.getItem('userInfo')
      
      if (token && userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          this.userInfo = userInfo
          this.token = token
          this.isLoggedIn = true
        } catch (error) {
          this.clearUserInfo()
        }
      }
    }
  }
})